package com.bluegalaxy.sitescore.controller;

import java.io.File;
import java.io.InputStream;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.bluegalaxy.sitescore.common.UploadUtil;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Permission;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
//import sun.org.mozilla.javascript.internal.json.JsonParser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 上传服务
 * </p>
 * <p>
 * 头像上传控件：<br>
 * http://www.fullavatareditor.com/index.html
 * </p>
 * 
 * @author
 * @Date 2016-04-13
 */
@Controller
@RequestMapping("/siteFile")
public class UploadController extends BaseController {
	protected  static String pathStr="fileUpload";
	@ResponseBody
	@Permission(action = Action.Skip)
	@RequestMapping(value = "/upLoad",method = RequestMethod.POST)
	public String upLoad(HttpServletRequest request,HttpServletResponse response)  throws Exception{
		request.setCharacterEncoding("UTF-8");

		Map<String, Object> json = new HashMap<String, Object>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		/** 页面控件的文件流* */
		MultipartFile multipartFile = null;
		Map map =multipartRequest.getFileMap();
		for (Iterator i = map.keySet().iterator(); i.hasNext();) {
			Object obj = i.next();
			multipartFile=(MultipartFile) map.get(obj);
		}
		/** 获取文件的后缀* */
		String filename = multipartFile.getOriginalFilename();
		String path = UploadUtil.writeFile(filename, getPhysicalPath(pathStr), multipartFile.getInputStream());
		json.put("fileName", path);
		json.put("message", "文件上传成功");
		json.put("status", true);
		return toJson(json);

	}

	private String getPhysicalPath(String path) {
		String servletPath = this.request.getServletPath();
		String realPath = this.request.getSession().getServletContext().getRealPath(servletPath);
		return (new File(realPath)).getParent() + "/" + path;
	}
}
